package com.fita.tencent.utils;

import java.security.AlgorithmParameters;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;  

/**
 * AES解密算法类
 * 
 * @author wangliwang
 *
 */
public abstract class AESUtils {
    
    public static final Logger logger = LoggerFactory.getLogger(AESUtils.class);
    
    public static boolean initialized = false;  
    
    /**
     * AES解密
     * 
     * @param content
     * @param keyByte
     * @param ivByte
     * @return
     * @throws Exception 
     * @throws InvalidKeyException 
     */
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidKeyException, Exception {
        
        initialize();
        
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        Key sKeySpec = new SecretKeySpec(keyByte, "AES");
        
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化 
        byte[] result = cipher.doFinal(content);
        
        return result;
    }
    
    /**
     * initialize flag
     */
    public static void initialize(){  
        if (initialized) return;  
        Security.addProvider(new BouncyCastleProvider());  
        initialized = true;  
    }
    
    /**
     * generate iv
     * 
     * @param iv
     * @return
     * @throws Exception
     */
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{  
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");  
        params.init(new IvParameterSpec(iv));  
        return params;  
    }  
}